package com.audaque.springboot.foshanupload.web.httpclientdemo.ieg.token;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.audaque.springboot.foshanupload.web.exception.RException;
import com.audaque.springboot.foshanupload.web.httpclientdemo.ieg.token.model.IegAuthorizeTokenReq;
import com.audaque.springboot.foshanupload.web.httpclientdemo.ieg.token.model.IegAuthorizeTokenVo;
import com.audaque.springboot.foshanupload.web.httpclientdemo.ieg.token.model.IegGetV2TokenReq;
import com.audaque.springboot.foshanupload.web.httpclientdemo.ieg.token.model.IegGetV2TokenVo;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class IegTokenProvider {

    @Setter
    private String v2Token;
    @Autowired
    private IegTokenProperties iegTokenProperties;

    @Autowired
    private ObjectMapper objectMapper;


    public String getV2Token() throws Exception {
        if (StringUtils.isBlank(v2Token)) {
            v2Token = getV2TokenByHutool();
        }
        return v2Token;
    }

    public Boolean authorize(String v2Token) throws Exception {
        String tokenKey = iegTokenProperties.getTokenKey();
        String url = iegTokenProperties.getAuthorizeUrl();
        IegAuthorizeTokenReq req = IegAuthorizeTokenReq.builder().token(v2Token).build();
        String body = objectMapper.writeValueAsString(req);

        String result = null;
        try {
            result = HttpRequest.post(url)
                    .header(tokenKey, v2Token)//头信息，多个头信息多次调用此方法即可
                    .body(body)
                    .execute().body();
        } catch (Exception e) {
            throw new RException("验证Token接口 调用过程中异常 1000086 %s",e.getMessage());
        }
        if (StringUtils.isBlank(result)) {
            throw new RException("验证Token接口 响应异常 1000086 无响应");
        }
        log.debug("验证Token接口 1000086 result {}" ,result);

        IegAuthorizeTokenVo rsp = null;
        try {
            rsp = (IegAuthorizeTokenVo) objectMapper.readerFor(IegAuthorizeTokenVo.class).readValue(result);
        } catch (Exception e) {
            throw new RException("验证Token接口 反序列化异常 1000086 %s", e.getMessage());
        }
        if (rsp==null) {
            return false;
        }
        if (rsp.getExp() == null || rsp.getExp() <= 0) {
            return false;
        }
        return true;
    }


    /**
     * 请求 v2 接口生成 v2 token
     *
     * @return
     */
    private String getV2TokenByHutool() throws Exception {
        String token;
        String userName = iegTokenProperties.getUserName();
        String userAuthKey = iegTokenProperties.getUserAuthKey();
        String tokensUrl = iegTokenProperties.getTokensUrl();
        // token 的有效期，不填的话，默认有效时间是 24 小时，可以根据自行需要调整, 最大不超过 24 小时
        //单位：秒
        Integer ttl = 24*60*60;
        IegGetV2TokenReq req = IegGetV2TokenReq.builder().user(userName).key(userAuthKey).ttl(ttl).build();
        String body = objectMapper.writeValueAsString(req);
        log.debug("getV2Token接口 1000086 调用中");
        String result = null;
        try {
            result = HttpUtil.post(tokensUrl, body);
        } catch (Exception e) {
            throw new RException("getV2Token接口 调用过程中异常 1000086 %s",e.getMessage());
        }
        if (StringUtils.isBlank(result)) {
            throw new RException("getV2Token接口 响应异常 1000086 无响应");
        }
        log.debug("getV2Token接口 1000086 result {}" ,result);

        IegGetV2TokenVo rsp = null;
        try {
            rsp = (IegGetV2TokenVo) objectMapper.readerFor(IegGetV2TokenVo.class).readValue(result);
        } catch (Exception e) {
            throw new RException("getV2Token接口 反序列化异常 1000086 %s", e.getMessage());
        }
        if (rsp!=null&&rsp.getCode() != null) {
            throw new RException("getV2Token接口 响应异常 1000086 %s", rsp.getMsg());
        }
        return rsp.getToken();
    }


}
